<template>
  <DialogCom :draggable="true" :title="title" :width="'500'" :visible="isVisible" @close="close" @confirm="confirm">
    <template v-slot:content>
      <el-form ref="ruleFormRef" :model="formData" :rules="rules" label-width="90px" class="demo-ruleForm" status-icon>
        <el-form-item label="文件:" prop="geojson">
          <div class="path">
            <el-input v-model="formData.geojson" placeholder="上传GeoJSON文件" disabled />
            <input v-show="false" ref="upfileRef" type="file" title=" " @change="upLoadFile" multiple="multiple"
              style="display: none" />
            <el-button class="common-btn" @click="selectFile">上传</el-button>
          </div>
        </el-form-item>
        <el-form-item label="高程:" prop="height" v-if="type == 'HeightMask'">
          <el-input v-model="formData.height" type="number" :step="1" :min="0" @change="editHandle" />
        </el-form-item>
      </el-form>
    </template>
  </DialogCom>
</template>

<script setup>
import { ref, defineProps } from 'vue'
import DialogCom from '@/components/common/DialogCom.vue'
import { upShpZip, upShp, reqGetShpFeatures } from '@/api/terrainrtsApi'
import { ElMessage } from 'element-plus'
import loading from "@/api/loading"


// 上传文件
const upfileRef = ref(null)
let arr = []
let fromDataArr = []
const selArr = ref([])
const ruleFormRef = ref('')
const props = defineProps({
  isVisible: {
    type: Boolean,
    default: false,
  },
  close: {
    type: Boolean,
    default: false,
  },
  title: {
    type: String,
    default: '',
  },
  type: {
    type: String,
    default: '',
  },
})
const emits = defineEmits(['close', 'confirm'])
const formData = ref({
  geojson: '',
  serverPath: '',
  features: '',
  height: 0,
})

const rules = ref({
  geojson: [{ required: true, message: '请上传GeoJSON文件', trigger: 'blur' }],
  height: [{ required: true, message: '请输入高程', trigger: 'blur' }],
})

const selectFile = () => {
  upfileRef.value.click()
}

const editHandle = (value) => {
  // 将输入值强制转换为数字，并确保不小于 0.1
  const numValue = Number(value);
  if (numValue <= 0 || isNaN(numValue)) {
    formData.value.height = 0
  }
}

const upLoadFile = async (e) => {
  const files = e.target.files
  if (files.length === 0) return

  // 重置状态
  formData.value.geojson = ''
  formData.value.features = ''

  const file = files[0]
  const reader = new FileReader()

  reader.onload = (event) => {
    try {
      const content = event.target.result
      const geojson = JSON.parse(content)
      console.log("geojson", geojson);


      // 验证是否包含Polygon
      if (!containsPolygon(geojson)) {
        throw new Error('文件中未包含任何Polygon类型的地理数据')
      }

      // 更新表单数据
      formData.value.geojson = file.name
      formData.value.features = geojson.features.filter(feature => {
        return feature &&
          feature.geometry &&
          (feature.geometry.type === 'Polygon' || feature.geometry.type === 'MultiPolygon')
      }).map(feature => {
        return {
          exterior: feature.geometry.coordinates[0]
        }
      })

      ElMessage.success('GeoJSON文件验证通过，包含Polygon数据')

    } catch (error) {
      ElMessage.error(`文件错误: ${error.message}`)
      console.error('GeoJSON解析错误:', error)
      // 清空文件输入
      e.target.value = ''
    }
  }

  reader.readAsText(file)
}

// 验证是否包含Polygon类型的GeoJSON
const containsPolygon = (data) => {
  try {
    // 基本结构检查
    if (typeof data !== 'object' || data === null) {
      return false
    }
    if (!('type' in data)) {
      return false
    }

    // 检查FeatureCollection
    if (data.type === 'FeatureCollection') {
      if (!Array.isArray(data.features) || data.features.length === 0) {
        return false
      }

      // 检查是否至少有一个Polygon
      return data.features.some(feature => {
        return feature &&
          feature.geometry &&
          (feature.geometry.type === 'Polygon' || feature.geometry.type === 'MultiPolygon')
      })
    }

    // 检查单个Feature
    if (data.type === 'Feature') {
      return data.geometry &&
        (data.geometry.type === 'Polygon' || data.geometry.type === 'MultiPolygon')
    }

    // 检查单个几何对象
    if (data.type === 'Polygon' || data.type === 'MultiPolygon') {
      return true
    }

    return false
  } catch {
    return false
  }
}

const close = () => {
  emits('close')
}
// 确认
const confirm = () => {
  ruleFormRef.value.validate((valid) => {
    if (!valid) return
    emits('confirm', {
      features: formData.value.features,
      height: Number(formData.value.height)
    })
  })
}
</script>

<style scoped>
.el-form-item .el-textarea,
.el-form-item .el-select,
.el-form-item .el-input {
  width: 300px !important;
}

.item {
  width: 300px;
}

.path {
  display: grid;
  grid-template-columns: 300px 70px;
  grid-column-gap: 5px;
}
</style>
